<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="item-form"
    >
      <ElRow :gutter="16">
        <ElCol :span="12">
          <ElFormItem label="商品编码" prop="itemCode">
            <ElInput
              v-model="formData.itemCode"
              placeholder="请输入商品编码"
              :disabled="type === 'edit'"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="商品名称" prop="itemName">
            <ElInput v-model="formData.itemName" placeholder="请输入商品名称" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="商品分类" prop="categoryId">
            <ElTreeSelect
              v-model="formData.categoryId"
              :data="categoryTreeData"
              :props="{ label: 'categoryName', value: 'id' }"
              placeholder="请选择商品分类"
              clearable
              filterable
              check-strictly
              :render-after-expand="false"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="商品品牌" prop="brandId">
            <ElSelect
              v-model="formData.brandId"
              placeholder="请选择商品品牌"
              clearable
              filterable
              style="width: 100%"
            >
              <ElOption
                v-for="brand in brandList"
                :key="brand.id"
                :label="brand.brandName"
                :value="brand.id"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="计量单位" prop="unit">
            <ElInput
              v-model="formData.unit"
              placeholder="请输入计量单位，如：个、件、箱"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="商品状态" prop="status">
            <ElRadioGroup v-model="formData.status">
              <ElRadio :label="1">启用</ElRadio>
              <ElRadio :label="0">禁用</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="商品描述" prop="remark">
            <ElInput
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入商品描述"
              maxlength="500"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <!-- SKU信息 -->
      <ElDivider content-position="left">
        <span class="divider-title">SKU信息</span>
      </ElDivider>

      <div class="sku-section">
        <div class="sku-header">
          <ElButton type="primary" size="small" @click="addSku">
            <ElIcon><Plus /></ElIcon>
            添加SKU
          </ElButton>
          <ElText type="info" size="small"> 至少需要添加一个SKU规格 </ElText>
        </div>

        <div class="sku-list">
          <div
            v-for="(sku, index) in formData.skuList"
            :key="index"
            class="sku-item"
          >
            <ElCard shadow="never" class="sku-card">
              <template #header>
                <div class="sku-card-header">
                  <span>SKU {{ index + 1 }}</span>
                  <ElButton
                    type="danger"
                    text
                    size="small"
                    @click="removeSku(index)"
                    :disabled="formData.skuList.length <= 1"
                  >
                    <ElIcon><Delete /></ElIcon>
                    删除
                  </ElButton>
                </div>
              </template>

              <ElRow :gutter="12">
                <ElCol :span="8">
                  <ElFormItem
                    :prop="`skuList.${index}.skuCode`"
                    :rules="skuRules.skuCode"
                    label="SKU编码"
                    label-width="80px"
                  >
                    <ElInput
                      v-model="sku.skuCode"
                      placeholder="请输入SKU编码"
                    />
                  </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                  <ElFormItem
                    :prop="`skuList.${index}.skuName`"
                    :rules="skuRules.skuName"
                    label="SKU名称"
                    label-width="80px"
                  >
                    <ElInput
                      v-model="sku.skuName"
                      placeholder="请输入SKU名称"
                    />
                  </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                  <ElFormItem
                    :prop="`skuList.${index}.barcode`"
                    label="条形码"
                    label-width="80px"
                  >
                    <ElInput v-model="sku.barcode" placeholder="请输入条形码" />
                  </ElFormItem>
                </ElCol>

                <ElCol :span="12">
                  <ElFormItem
                    :prop="`skuList.${index}.specifications`"
                    label="规格描述"
                    label-width="80px"
                  >
                    <ElInput
                      v-model="sku.specifications"
                      placeholder="如：红色/L码、500ml等"
                    />
                  </ElFormItem>
                </ElCol>

                <ElCol :span="6">
                  <ElFormItem
                    :prop="`skuList.${index}.weight`"
                    label="重量(kg)"
                    label-width="80px"
                  >
                    <ElInputNumber
                      v-model="sku.weight"
                      :min="0"
                      :precision="3"
                      placeholder="重量"
                      style="width: 100%"
                    />
                  </ElFormItem>
                </ElCol>

                <ElCol :span="6">
                  <ElFormItem
                    :prop="`skuList.${index}.volume`"
                    label="体积(m³)"
                    label-width="80px"
                  >
                    <ElInputNumber
                      v-model="sku.volume"
                      :min="0"
                      :precision="6"
                      placeholder="体积"
                      style="width: 100%"
                    />
                  </ElFormItem>
                </ElCol>
              </ElRow>
            </ElCard>
          </div>
        </div>
      </div>
    </ElForm>

    <template #footer>
      <ElSpace>
        <ElButton @click="handleCancel">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
import { useWmsStore } from "@/store/modules/wms";
import { addItem, updateItem } from "@/api/wms/item";
import { ElMessage } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({ name: "WmsItemDialog" });

// Props
interface Props {
  visible: boolean;
  type: "add" | "edit";
  itemData?: WMS.Item.ItemInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  type: "add",
  itemData: null,
});

// Emits
interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "submit"): void;
}

const emit = defineEmits<Emits>();

// 状态管理
const wmsStore = useWmsStore();

// 表单引用
const formRef = ref<FormInstance>();

// 弹窗状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

const dialogTitle = computed(() => {
  return props.type === "add" ? "新增商品" : "编辑商品";
});

// 提交状态
const submitLoading = ref(false);

// 表单数据
const formData = ref<WMS.Item.CreateParams>({
  itemCode: "",
  itemName: "",
  categoryId: undefined,
  brandId: undefined,
  unit: "",
  status: 1,
  remark: "",
  skuList: [],
});

// 表单验证规则
const formRules: FormRules = {
  itemCode: [
    { required: true, message: "请输入商品编码", trigger: "blur" },
    { min: 2, max: 50, message: "商品编码长度在2-50个字符", trigger: "blur" },
  ],
  itemName: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 2, max: 100, message: "商品名称长度在2-100个字符", trigger: "blur" },
  ],
  categoryId: [
    { required: true, message: "请选择商品分类", trigger: "change" },
  ],
  unit: [{ required: true, message: "请输入计量单位", trigger: "blur" }],
  status: [{ required: true, message: "请选择商品状态", trigger: "change" }],
};

// SKU验证规则
const skuRules = {
  skuCode: [{ required: true, message: "请输入SKU编码", trigger: "blur" }],
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
};

// 计算属性
const categoryTreeData = computed(() => {
  return wmsStore.itemCategoryTreeList || [];
});

const brandList = computed(() => {
  return wmsStore.getActiveItemBrands || [];
});

// 监听弹窗显示
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      initFormData();
    }
  },
);

// 初始化表单数据
const initFormData = () => {
  if (props.type === "edit" && props.itemData) {
    // 编辑模式，填充数据
    formData.value = {
      id: props.itemData.id,
      itemCode: props.itemData.itemCode,
      itemName: props.itemData.itemName,
      categoryId: props.itemData.categoryId,
      brandId: props.itemData.brandId,
      unit: props.itemData.unit || "",
      status: props.itemData.status ?? 1,
      remark: props.itemData.remark || "",
      skuList: props.itemData.skuList || [],
    };

    // 如果没有SKU，添加一个默认的
    if (formData.value.skuList.length === 0) {
      addSku();
    }
  } else {
    // 新增模式，重置表单
    formData.value = {
      itemCode: "",
      itemName: "",
      categoryId: undefined,
      brandId: undefined,
      unit: "",
      status: 1,
      remark: "",
      skuList: [],
    };

    // 添加一个默认SKU
    addSku();
  }

  // 重置表单验证
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 添加SKU
const addSku = () => {
  formData.value.skuList.push({
    skuCode: "",
    skuName: "",
    barcode: "",
    specifications: "",
    weight: undefined,
    volume: undefined,
  });
};

// 删除SKU
const removeSku = (index: number) => {
  if (formData.value.skuList.length > 1) {
    formData.value.skuList.splice(index, 1);
  }
};

// 取消
const handleCancel = () => {
  dialogVisible.value = false;
};

// 提交
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value?.validate();

    submitLoading.value = true;

    if (props.type === "add") {
      await addItem(formData.value);
      ElMessage.success("新增商品成功");
    } else {
      await updateItem(formData.value);
      ElMessage.success("更新商品成功");
    }

    dialogVisible.value = false;
    emit("submit");
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.item-form {
  .divider-title {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .sku-section {
    .sku-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }

    .sku-list {
      .sku-item {
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        .sku-card {
          :deep(.el-card__header) {
            padding: 12px 16px;
            background-color: var(--el-fill-color-lighter);
          }

          :deep(.el-card__body) {
            padding: 16px;
          }

          .sku-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 500;
          }
        }
      }
    }
  }
}
</style>
